from django.contrib import admin
from django.contrib.admin.filters import DateFieldListFilter  # 导入日期过滤器
from import_export import resources, fields, widgets  # 添加widgets导入
from import_export.admin import ImportExportActionModelAdmin
from .models import Department, Contact
from import_export.formats import base_formats
from django.utils.html import format_html


# 先定义DepartmentAdmin
class DepartmentAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)

# 然后定义ContactResource
class ContactResource(resources.ModelResource):
    id = fields.Field(attribute='id', column_name='ID')
    order = fields.Field(attribute='order', column_name='排序')
    name = fields.Field(attribute='name', column_name='姓名')
    department = fields.Field(
        attribute='department',
        column_name='部门',
        widget=widgets.ForeignKeyWidget(Department, 'name')
    )
    position = fields.Field(
        attribute='position', 
        column_name='职位',
        default=''  # 添加默认值
    )
    phone = fields.Field(
        attribute='phone', 
        column_name='电话',
        default=''  # 添加默认值
    )
    short_code = fields.Field(
        attribute='short_code', 
        column_name='短号',
        default=''  # 添加默认值
    )
    avatar = fields.Field(
        attribute='avatar', 
        column_name='头像',
        default=''  # 添加默认值
    )
    # 新增性别字段
    gender = fields.Field(
        attribute='get_gender_display', 
        column_name='性别',
        default='U'
    )

    # 新增参加工作时间字段
    hire_date = fields.Field(
        attribute='hire_date', 
        column_name='参加工作时间',
        widget=widgets.DateWidget(format='%Y-%m-%d'),
        default=None
    )

    def before_import_row(self, row, **kwargs):
        # 确保部门存在，不存在则创建
        department_name = row.get('部门')
        if department_name:
            Department.objects.get_or_create(name=department_name)
        
        # 确保必填字段有值
        for field in ['职位', '电话', '短号']:
            if not row.get(field):
                row[field] = ''

    class Meta:
        model = Contact
        skip_unchanged = True
        report_skipped = False
        fields = ('id', 'order', 'name', 'department', 'position', 'phone', 'short_code', 'avatar', 'gender', 'hire_date')
        export_order = ('order', 'name', 'gender', 'department', 'position', 'phone', 'short_code', 'avatar', 'hire_date')

    def export(self, queryset=None, *args, **kwargs):
        return super().export(queryset, *args, **kwargs)

# 最后定义ContactAdmin
class ContactAdmin(ImportExportActionModelAdmin):
    resource_class = ContactResource
    list_display = ('id', 'order', 'avatar_preview', 'name', 'is_displayed', 'gender', 'department', 'position', 'phone', 'short_code', 'format_hire_date')
    list_editable = ('is_displayed', 'order')
    list_filter = ('department', 'gender', ('hire_date', DateFieldListFilter), 'is_displayed')
    search_fields = ('name', 'phone', 'short_code', 'position')
    list_per_page = 20
    ordering = ('department', 'order')
    list_display_links = ('name',)
    
    # 字段分组
    fieldsets = (
        ('常用信息', {
            'fields': ('order','name', 'department', 'phone','short_code'),
            'classes': ('wide', 'extrapretty'),
        }),
        ('其他信息', {
            'fields': ('gender','position', 'avatar','hire_date'),
            'classes': ('wide', 'collapse'),
        }),
    )
    
    def get_export_fields(self):
        return [
            ('id', 'ID'),
            ('order', '排序'),
            ('name', '姓名'),
            ('gender', '性别'),
            ('department__name', '部门'),
            ('position', '职位'),
            ('phone', '电话'),
            ('short_code', '短号'),
            ('avatar', '头像'),
            ('hire_date', '参加工作时间')
        ]
    
    def get_export_formats(self):
        return [
            base_formats.XLSX,  # 只保留XLSX格式
            base_formats.CSV,
            base_formats.JSON,
            base_formats.HTML,
            base_formats.TSV
        ]
    
    def get_export_resource_kwargs(self, request, *args, **kwargs):
        return {
            'request': request,
            'formats': ['xlsx', 'csv', 'json', 'html', 'tsv']  # 移除了xls
        }
    
    def get_import_resource_class(self):
        return ContactResource
    
    def get_export_resource_class(self):
        return ContactResource

    # 自定义方法，格式化参加工作时间为年-月
    def format_hire_date(self, obj):
        if obj.hire_date:
            return obj.hire_date.strftime('%Y/%m')
        return ''
    format_hire_date.short_description = '参加工作时间'

    # 调整short_code编辑框宽度
    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'short_code':
            kwargs['widget'] = admin.widgets.AdminTextInputWidget(attrs={'size': '5', 'style': 'width: 60px;'})
        return super().formfield_for_dbfield(db_field, **kwargs)


    # 头像点击事件  点击头像弹出大图
    def avatar_preview(self, obj):
        return format_html('''
        <img src="{}" width="50" height="50" title="点击查看大图" onclick="showImage(event, '{}')"/>
        <script>
            function showImage(event, imgUrl) {{
                event.preventDefault();
                const x = event.clientX;
                const y = event.clientY;
                const newWindow = window.open(imgUrl, '_blank', 'width=400,height=400,left=' + (x + 10) + ',top=' + (y + 10) + ',resizable=yes');
            }}
        </script>
        ''', obj.avatar_url, obj.avatar_url)
    avatar_preview.short_description = '头像预览'


# 后台美化
admin.site.site_header = '通讯录管理后台'  # 设置header
admin.site.site_title = '通讯录管理信息系统'   # 设置title
admin.site.index_title = '首页'    #页面标题+后台右上角第二标题
 




admin.site.register(Department, DepartmentAdmin)
admin.site.register(Contact, ContactAdmin)
